package com.xuecheng.content.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.domain.mapper.CourseMarketMapper;
import com.xuecheng.content.domain.model.dto.CourseBaseMarketDto;
import com.xuecheng.content.domain.model.entity.CourseBase;
import com.xuecheng.content.domain.model.enums.CourseChargeEnum;
import com.xuecheng.content.domain.service.CourseBaseService;
import com.xuecheng.content.domain.service.CourseCategoryService;
import com.xuecheng.content.domain.service.CourseMarketService;
import com.xuecheng.content.domain.model.entity.CourseMarket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 课程营销信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseMarketServiceImpl extends ServiceImpl<CourseMarketMapper, CourseMarket> implements CourseMarketService {

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private CourseCategoryService courseCategoryService;

    @Override
    public void saveOrUpdateCourseMark(CourseMarket courseMarket) {
        if (courseMarket.getCharge().equals(CourseChargeEnum.CHARGE.getCode()) &&
                Objects.isNull(courseMarket.getPrice()) || courseMarket.getPrice().floatValue() <= 0){
            throw new XueChengPlusException("课程为收费价格不能为空且必须大于0");
        }
        CourseMarket findCourseMark = courseMarketMapper.selectById(courseMarket.getId());
        // 存在就更新，不存在就插入
        if (Objects.isNull(findCourseMark)){
            courseMarketMapper.insert(courseMarket);
        } else {
            BeanUtils.copyProperties(courseMarket, findCourseMark);
            findCourseMark.setId(courseMarket.getId());
            courseMarketMapper.updateById(findCourseMark);
        }
    }

    @Override
    public CourseBaseMarketDto queryCourseBaseMarket(Long id) {
        CourseBase courseBase = courseBaseService.getById(id);
        if (Objects.isNull(courseBase)){
            return new CourseBaseMarketDto();
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        CourseBaseMarketDto res = BeanUtil.copyProperties(courseBase, CourseBaseMarketDto.class);
        if (Objects.nonNull(courseMarket)){
            BeanUtils.copyProperties(courseMarket, res);
        }
        // 查询课程分类名称
        res.setStName(courseCategoryService.getById(courseBase.getSt()).getName());
        res.setMtName(courseCategoryService.getById(courseBase.getMt()).getName());

        return res;
    }
}
